package com.simulation.superlotto.common.exception;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常拦截
 */
@ControllerAdvice // 可指定包前缀，例如：(basePackages = "com.pj.controller.admin")
public class GlobalException  {

    private final static String DEFAULT_ERROR_VIEW = "error";//错误信息页

    @Autowired
    private ErrorInfoBuilder errorInfoBuilder;//错误信息的构建工具


     //全局异常拦截
//    @ResponseBody
//    @ExceptionHandler
//    public ResponseJson handlerException(Exception e) {
//        // 打印堆栈，以供调试
//        System.out.println(e.getMessage());
////        e.printStackTrace();
//        //如果属于自定义异常
////        if (e instanceof ApiException) {
////            return ResponseJson.failed(e.getMessage());
////        }
//        //其他异常返回失败
//        return ResponseJson.failed(e.getMessage());
//    }


    /**
     * 根据业务规则,统一处理异常。
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object exceptionHandler(HttpServletRequest request, Throwable error) {

        //1.若为AJAX请求,则返回异常信息(JSON)
        if (isAjaxRequest(request)) {
            return errorInfoBuilder.getErrorInfo(request,error);
        }
        //2.其余请求,则返回指定的异常信息页(View).
        ModelAndView errorInfo = new ModelAndView(DEFAULT_ERROR_VIEW, "errorInfo", errorInfoBuilder.getErrorInfo(request, error));
        System.out.println(errorInfo);
        return errorInfo;
    }


    private boolean isAjaxRequest(HttpServletRequest request) {

        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }


}

